define(['service','lodash.min','swiper.min','../config/ace-config'], function(Service,_,Swiper,Config) {
  return View.extend({
    events: {
      'click .appDown': 'onDownloadClick',
      'click .userimg': 'qcodeScan'
    },
    info:{},

    qID:function(id){
      return document.getElementById(id);
    },

    render: function() {
      console.log(Config)
      var state = this.checkNetworkState();
      this.listTmp = this.qID('module-list-template').innerHTML
      this.itemTmp = this.qID('module-item-template').innerHTML
      this.slideTmp = this.qID('slide-template').innerHTML
      this.modalTmp = this.qID('modal-template').innerHTML

      window.networkStateChange = this.networkStateChange.bind(this)
      window.moduleInstallState = this.moduleInstallState.bind(this)
      window.moduleUninstallState = this.moduleUninstallState.bind(this)
      window.moduleUpgradeState = this.moduleUpgradeState.bind(this)
      window.updateModuleProgress = this.updateModuleProgress.bind(this)

      this.startSwiper();
      this.startContentSwiper();
      if(state==='none'){
        this.getLocalModuleList();
      }else {
        this.getModuleList();
      }
      // this.getModuleList();
    },

    // 启动二维码扫描
    qcodeScan: function(){
      var _this = this;
      try{
        var successFunc = function(result){
          var info = "We got a barcode\n" +
                "Result: " + result.text + "\n" +
                "Format: " + result.format + "\n" +
                "Cancelled: " + result.cancelled;
          _this.alertInfo(info,function(){
            window.open(result.text,'_blank')
          })
        };
        var errorFunc = function(error){
          _this.alertInfo("Scanning failed: " + error);
        };
        Service.exec(successFunc.bind(_this), errorFunc.bind(_this), "BarcodeScanner", "scan", []);
      }catch(e){_this.alertInfo(e)}
    },

    //弹出对话框
    alertInfo:function(info,cb){
      $.hidePreloader();
      $.closeModal('.downloadModal')
      $.alert(info,cb)
    },

    // 获取模块列表
    getModuleList:function(){
      var _this = this;
      try{
      var completeFunc = function(){
        $('#circularG').hide()
        _this.loadFinish = true;
        //图标出错是使用默认已安装头像
        $('.mlgo').on('error',function(){
          // console.log('3333333')
          this.src = "./images/icon_blue.png";
        })
      }
      var successFunc = function(data){
        data = JSON.parse(data);
        if(data.list&&data.list.length>0){
          data = _this.formatData(data);
          _this.renderModulesList(data);
          _this.checkUnnecessaryModule(data);
        }else {
          _this.showEmptyBox();
        }
        completeFunc();
      };
      var errorFunc = function(err){
        _this.alertInfo(err)
        _this.showEmptyBox()
        completeFunc();
      };
        Service.exec(successFunc.bind(_this), errorFunc.bind(_this), "ModuleOperation", "getAllModuleList", []);
        setTimeout(function(){
          if(!_this.loadFinish){
            completeFunc()

            $.modal({
              text:'当前网络异常，请选择重试或者读取本地模块！',
              buttons:[{
                text:"重试",
                onClick: function() {
                  location.reload()
                }
              },{
                text:"读取本地模块",
                onClick: function() {
                  _this.getLocalModuleList('读取~！')
                }
              }]
            })
          }
        },10*1000)
      }catch(e){_this.alertInfo(e)}
    },

    // 获取本地模块列表
    getLocalModuleList:function(){
      var _this = this;
      try{
        var completeFunc = function(){
          $('#circularG').hide()
          _this.loadFinish = true;
          //图标出错是使用默认已安装头像
          $('.mlgo').on('error',function(){
            this.src = "./images/icon_blue.png";
          })
        }
        var successFunc = function(data){
          data = JSON.parse(data);
          if(data.list&&data.list.length>0){
            data = _this.formatData(data);
            _this.renderModulesList(data);
          }else{
            _this.showEmptyBox()
          }
          completeFunc()
        };
        var errorFunc = function(err){
          _this.alertInfo(err)
          _this.showEmptyBox()
          completeFunc()
        };
        Service.exec(successFunc.bind(_this), errorFunc.bind(_this), "ModuleOperation", "getInstalledModuleList", []);
      }catch(e){_this.alertInfo(e)}
    },

    //删除模块
    deleteModule:function (identifier) {
      if(!identifier) return;
      var _this = this;
      var successFunc = function(data){_this.alertInfo(data)};
      var errorFunc = function(err){_this.alertInfo(err)};
      try{
        Service.exec(successFunc.bind(_this), errorFunc.bind(_this), "ModuleOperation", "deleteModule", [identifier]);
      }catch(e){_this.alertInfo(e)}
    },

    //删除不需要的模块
    checkUnnecessaryModule: function(list){
      var _this = this;
      var successFunc = function(data){
        data = JSON.parse(data);
        if(data.list&&data.list.length>0){
          data = _this.formatData(data);
          var tmp = {};
          list = _.flatten(list)
          data = _.flatten(data)
          _.map(list,function(item,i,arr){
            tmp[item.identifier] = item;
          })
          _.map(data,function(item,i,arr){
            if(!tmp[item.identifier]){
              _this.deleteModule(item.identifier);
            }
          })
        }
      };
      var errorFunc = function(err){_this.alertInfo(err)};
      try{
        Service.exec(successFunc.bind(_this), errorFunc.bind(_this), "ModuleOperation", "getInstalledModuleList", []);
      }catch(e){_this.alertInfo(e)}
    },

    // 格式模块信息
    formatItem:function(item){
      var defaultImgTag = "module_version_icon"
      var installedImg = "./images/icon_blue.png";
      var uninstallImg = "./images/icon_gray.png";
      switch(item.moduleType){
        case 2:
          item.moduleStatus = 1;//已下载
          break;
        case 5:
        case 6:
          item.moduleStatus = 2;//可更新
          break;
        default:
          item.moduleStatus = 0;//未下载
      }
      if(item.moduleStatus>0){
        if(item.iconUrl&&item.iconUrl.indexOf(defaultImgTag)<0){
          item.logo = "../"+item.identifier+"/icon.png"
        }else{
          item.logo = installedImg;
        }
      }else{
        item.logo = uninstallImg
      }
      item.logo += "?time="+Date.now()
      this.info[item.identifier] = {
        moduleStatus: item.moduleStatus,
        identifier: item.identifier,
        iconUrl: item.iconUrl,
        logo: item.logo,
        releaseNote: item.releaseNote,
        version: item.version,
        name: item.name
      };
      return item;
    },

    // 格式化数据到展示列表
    formatDataToList:function(data){
      var total = data.length;
      var pagesize = 9;
      var pages = Math.ceil(total/pagesize)
      var dataset = [];
      console.log('totle:%s,pagesize:%s,pages:%s',total,pagesize,pages);
      for(var currPage= 0;currPage<pages;currPage++){
        if(!dataset[currPage]){
          dataset[currPage] = [];
        }
        for(var i = 0;i<pagesize;i++){
          var currModule = data[currPage*9+i]
          if(currModule){
            dataset[currPage].push(currModule)
          }
        }
      }
      return dataset
    },

    // 格式整体数据
    formatData:function(data){
      var mainModule = data.mainModuleTag
      data = data.list;
      console.log(data);
      var _this = this;
      var nData = [];
      _.each(data,function(item,i){
        item = _this.formatItem(item,i)
        if(item.identifier===mainModule)return;
        nData.push(item)
      })
      // console.log(nData);
      data = _this.formatDataToList(nData)
      return data
    },

    // 渲染单个模块
    renderModuleItem:function(item){
      var compiled = _.template(this.itemTmp);
      var itemStr = compiled({item:item})
      // console.log(itemStr);
      return itemStr
    },

    // 渲染模块列表
    renderModulesList:function(data){
      var _this = this;
      var pages = data.length;
      var compiled = _.template(_this.listTmp);
      var slides = _this.contentSwiper.slides
      for(var i=0;i<pages;i++){
        var page = data[i]
        var pageData = _.map(page,function(item,i){
          var itemStr = _this.renderModuleItem(item)
          return {html:itemStr};
        })
        var htmlStr = compiled(pageData);
        if(i===0){
          slides[0].innerHTML = htmlStr
        }else{
          _this.renderSlide(htmlStr);
        }
      }
    },

    // 渲染一页模块列表
    renderSlide:function(data){
      var compiled = _.template(this.slideTmp);
      var htmlStr = compiled({html:data});
      this.contentSwiper.appendSlide(htmlStr);
    },

    // 更新单个模块显示
    updateModuleItem:function(identify,isDelete){
      if(this.info[identify]){
        var itemInfo = this.info[identify];
        itemInfo.moduleType = isDelete?0:2;
        // alert(JSON.stringify(itemInfo))
        itemInfo = this.formatItem(itemInfo);
        // alert(JSON.stringify(itemInfo))
        var htmlStr = this.renderModuleItem(itemInfo);
        $('[data-id="'+identify+'"]').replaceWith(htmlStr)
      }
    },

    // 初始化bandner
    startSwiper: function() {
      var isLoop = $('.bandner-container .swiper-slide').length>1
      if(Swiper){
        this.bandnerSwiper = new Swiper('.bandner-container', {
          autoplayDisableOnInteraction: false,
          pagination: '.bandner-pagination',
          autoplay: 1000,
          loop:isLoop
        });
      }
    },

    // 初始化内容
    startContentSwiper: function() {
      if (Swiper) { //初始化swiper
        this.contentSwiper = new Swiper('.content-container',{
          pagination: '.content-pagination'
        })
      }
    },
    installModule:function (identify) {
      var _this = this;
      try{
        Service.exec(function(data){
          // if(typeof data === "string") data = JSON.parse(data);
          // if("success"===data.result){
          //   _this.moduleDownloadStart(data.identify);
          // }
        }, function(err){
          _this.alertInfo(err)
        }, "ModuleOperation", "installModule", [identify]);
      }catch(e){_this.alertInfo(e)}
    },
    upgradeModule:function (identify) {
      var _this = this;
      try{
        Service.exec(function(data){
        }, function(err){
          _this.alertInfo(err)
        }, "ModuleOperation", "upgradeModule", [identify]);
      }catch(e){_this.alertInfo(e)}
    },
    downloadModule:function(info){
      var id = info.identifier
      if(!id) return this.alertInfo("该模块id不存在")
      $.showPreloader('下载中');
      try{
        if(info.moduleStatus==2){
          this.upgradeModule(id)
        }else{
          this.installModule(id)
        }
      }catch(e){ alert(e) }
    },
    moduleDownloadStart:function(identify) {
      this.alertInfo('moduleDownloadStart====>' + identify );
      // this.updateModuleItem(identify);
    },
    moduleInstallState:function(identify,state){
      if(state == 'true') {
        this.alertInfo("模块:" + identify + "安装成功!");
        // if(this.info.hasOwnProperty(identify)){
        //   this.info[identify].moduleType = 2;
        //   this.
        // }
        this.updateModuleItem(identify);
      } else {
        this.alertInfo("模块:" + identify + "安装失败!");
      }
    },
    moduleUninstallState:function(identify,state) {
      if(state == 'true') {
        this.alertInfo("模块:" + identify + "删除成功!");
        this.updateModuleItem(identify,state);
      } else {
        this.alertInfo("模块:" + identify + "删除失败!");
      }
    },
    moduleUpgradeState:function(identify,state) {
      if(state == 'true') {
        this.alertInfo("模块:" + identify + "升级成功!");
        this.updateModuleItem(identify);
      } else {
        this.alertInfo("模块:" + identify + "升级失败!");
      }
    },
    updateModuleProgress:function(identify,progress) {
      // $.alert('updateModuleProgress====>' + identify + 'progress===>' + progress );
      try{
        var moduleItem = $('[data-id="'+identify+'"]');
        if(moduleItem.length>0){
          moduleItem.find('.appDown').hide();
          moduleItem.find('.module-logo').css({height:40*progress/100+"px"})
        }
      }catch(e){this.alertInfo(e)}
    },
    checkNetworkState:function(){
      var networkState;
      if(navigator.connection){
        networkState = navigator.connection.type;
      }
      return networkState?networkState:'none'
    },
    // 网络情况监听
    networkStateChange:function(state){
      var _this = this;
      // alert(!!!_this.loadFinish)
      // alert('网络状态:'+state);
      // alert(state==="true"?"开网":"断网")
      if(state==="false"&&!_this.loadFinish){
        $('#circularG').hide()
        _this.loadFinish = true;
        $('.mlgo').on('error',function(){this.src = "./images/icon_blue.png";})
        $.modal({
          text:'当前网络异常，请选择重试或者读取本地模块！',
          buttons:[{
            text:"重试",
            onClick: function() {
              location.reload()
            }
          },{
            text:"读取本地模块",
            onClick: function() {
              _this.getLocalModuleList('读取~！')
            }
          }]
        })
      }
    },

    onDownloadClick:function(e) {
      var _this = this;
      e.preventDefault()
      try{
        var el =  e.currentTarget;
        // if(!el.dataset.hasOwnProperty('id')) return;
        var mid = el.dataset.id;
        var type = el.dataset.type;
        var method = type==="download"?"getUninstallModuleList":"getUpgradeableModuleList";
        // $.showPreloader('正在获取模块信息');
        var successFunc = function (data){
          console.log(data);
          _this.alertInfo(data)
          try{
            data = JSON.parse(data);
            $.hidePreloader();
            if(data){
              var currModule = _.find(data.list,function(item){ return item.identifier === mid })
              if(!currModule) return _this.alertInfo('暂无模块信息')
              var info = _this.formatItem(currModule)
              _this.showMask(info);
            }
          }catch(e){_this.alertInfo(e)}
        }
        var errorFunc = function (err){
          _this.alertInfo(err)
        }
        Service.exec(successFunc.bind(_this), errorFunc.bind(_this), "ModuleOperation", method, []);

      }catch(e){_this.alertInfo(e)}
    },
    showEmptyBox: function(){
      $('.emptyMsgBox').show();
    },
    hideEmptyBox: function(){
      $('.emptyMsgBox').hide();
    },
    showMask: function(info) {
     var _this = this;
      try{
    //  var el =  e.currentTarget;
    //  if(el.dataset.hasOwnProperty('id')){
      // var id = el.dataset.id;
      // var info = this.info[id];
      if(info){
        var compiled = _.template(this.modalTmp);
        var htmlStr = compiled({item:info});
        // $('.maskLayer').html(htmlStr).removeClass("hidden");
        var downloadText = (info.moduleStatus==2?"升级":"下载")+"模块"
        var modal = $.modal({
          title: '模块详情',
          text:  htmlStr,
          extraClass: 'downloadModal',
          // afterText: '<span class="dialog-tips">强制升级，否则无法正常使用该模块！</span>',
          buttons: [
            {
              text: downloadText,
              onClick: function () {
                _this.downloadModule(info)
              }
            },
            {text: '不需要'}
            ]
          })
        modal.classList.add('downloadModal');
          // console.dir(modal)
        }
      // }
      }catch(e){_this.alertInfo(e)}
    }
  });
});
